package fms.service;

import fms.dao.ServiceStatusService;
import fms.model.ServiceStatus;
import fms.mqAccessUtil.ActivemqReceiver;
import fms.util.ConfUtil;
import fms.util.ObjectUtil;
import fms.util.SysConstants;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.pool.PooledConnectionFactory;
import org.apache.activemq.transport.TransportListener;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import java.io.IOException;
import java.util.Date;


public class MainService implements TransportListener{

    private Logger logger = Logger.getLogger(MainService.class);

    private ServiceStatusService serviceStatusService = null;

    private ServiceStatus curActiveMQstatus = null;
    final ActiveMQConnectionFactory mqConnFactory= (ActiveMQConnectionFactory) ConfUtil.getSingletonApplicationContext().getBean("activeMQConnFactory");
    final ActivemqReceiver receiver = (ActivemqReceiver) ConfUtil.getSingletonApplicationContext().getBean("messageReceiver");

    public static void main(String[] args) {

        String logFilePath= ConfUtil.props.getProperty("log4jconfig");
        PropertyConfigurator.configure(logFilePath);
        MainService service = new MainService();
        service.start();
    }

    public void start() {
        // spring配置文件的基本功能，就是将要创建的类及其成员对象自动装配（new实例化）
        final ActiveMQConnectionFactory mqConnFactory= (ActiveMQConnectionFactory) ConfUtil.getSingletonApplicationContext().getBean("activeMQConnFactory");
        final ActivemqReceiver receiver = (ActivemqReceiver) ConfUtil.getSingletonApplicationContext().getBean("messageReceiver");
//        final MsmqReceiver msmqReceiver = (MsmqReceiver)applicationContext.getBean("messageMsmqReceiver");
        serviceStatusService = ConfUtil.getSingletonApplicationContextDao().getBean("serviceStatusService", ServiceStatusService.class);
        mqConnFactory.setTransportListener(this);

//        try {
        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    logger.info("SKYFMS系统核心处理服务V1.0.1已启动...");

                    curActiveMQstatus = serviceStatusService.findByServicecode(SysConstants.ACTIVEMQ_CODE);
                    // 如果，数据库中没有ACTIVEMQ状态信息
                    if (null == curActiveMQstatus) {
                        curActiveMQstatus = new ServiceStatus();
                    }
                    // 为了减轻数据库的压力，只有在状态发生变化的时候，对时间进行更新
                    // 如果，数据库中没有ACTIVEMQ状态信息 or 数据库中已有状态为异常的信息；就更新为正常
                    if ( ObjectUtil.isBlank(curActiveMQstatus.getStatus())
                            || curActiveMQstatus.getStatus().equals(SysConstants.SERVICE_EXCEPTION_CODE) ) {
                        curActiveMQstatus.setServiceName(SysConstants.ACTIVEMQ_CODE);
                        curActiveMQstatus.setServiceCode(SysConstants.ACTIVEMQ_CODE);
                        // 获取当前系统时间（北京时间）
                        curActiveMQstatus.setUpdateTime( new Date() );
                        curActiveMQstatus.setStatus(SysConstants.SERVICE_NORMAL_CODE);
                        serviceStatusService.saveOrUpdate(curActiveMQstatus);
                        logger.debug("ACTIVEMQ运行状态更新为正常！");
                    }
                    // 上面的语句不能写在recive后面，因为recive是一个死循环访问activeMQ，直到出现异常or停止服务
                    receiver.receive();

                } catch (Exception e) {
                    logger.error("SKYFMS系统核心处理服务异常：" + e.toString());
                    curActiveMQstatus = serviceStatusService.findByServicecode(SysConstants.ACTIVEMQ_CODE);
                    // 如果，数据库中没有ACTIVEMQ状态信息
                    if (null == curActiveMQstatus) {
                        curActiveMQstatus = new ServiceStatus();
                    }
                    // 为了减轻数据库的压力，只有在状态发生变化的时候，对时间进行更新
                    // 如果，数据库中没有ACTIVEMQ状态信息 or 数据库中已有状态为正常的信息，更新为异常
                    if ( ObjectUtil.isBlank(curActiveMQstatus.getStatus())
                            || curActiveMQstatus.getStatus().equals(SysConstants.SERVICE_NORMAL_CODE) ) {
                        curActiveMQstatus.setServiceName(SysConstants.ACTIVEMQ_CODE);
                        curActiveMQstatus.setServiceCode(SysConstants.ACTIVEMQ_CODE);
                        // 获取当前系统时间（北京时间）
                        curActiveMQstatus.setUpdateTime( new Date() );
                        curActiveMQstatus.setStatus(SysConstants.SERVICE_EXCEPTION_CODE);
                        serviceStatusService.saveOrUpdate(curActiveMQstatus);
                        logger.error("ACTIVEMQ运行状态更新为异常！");
                    }
                }
            }
        }).start();
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    msmqReceiver.recive();
//                }
//            }).start();
//            logger.info("消息接收服务启动...");

//        } catch (Exception e) {
//
//        }
    }

    public void stop() {
        System.exit(0);
    }

    @Override
    public void onCommand(Object o) {

    }

    @Override
    public void onException(IOException e) {

    }

    @Override
    public void transportInterupted() {

        curActiveMQstatus.setServiceName(SysConstants.ACTIVEMQ_CODE);
        curActiveMQstatus.setServiceCode(SysConstants.ACTIVEMQ_CODE);
        // 获取当前系统时间（北京时间）
        curActiveMQstatus.setUpdateTime( new Date() );
        curActiveMQstatus.setStatus(SysConstants.SERVICE_EXCEPTION_CODE);
        serviceStatusService.saveOrUpdate(curActiveMQstatus);
        logger.error("ACTIVEMQ运行状态更新为异常！");

    }

    @Override
    public void transportResumed() {

        curActiveMQstatus.setServiceName(SysConstants.ACTIVEMQ_CODE);
        curActiveMQstatus.setServiceCode(SysConstants.ACTIVEMQ_CODE);
        // 获取当前系统时间（北京时间）
        curActiveMQstatus.setUpdateTime( new Date() );
        curActiveMQstatus.setStatus(SysConstants.SERVICE_NORMAL_CODE);
        serviceStatusService.saveOrUpdate(curActiveMQstatus);
//        logger.debug("ACTIVEMQ运行状态更新为正常！");

    }
}